import React, {
  useEffect,
  useState,
  Ref,
  forwardRef,
  useImperativeHandle,
  useCallback,
  useRef,
} from 'react';
import Icon from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { Tree, Button } from 'antd';
import { InbizIcon } from '@inbiz/utils';
import { TextWidget, getMessage } from '@inbiz/react';
import { choeseData } from './index';
import { getCategoryTree } from './service';
import DocSearch from './DocSearch';
import DocList from './DocList';
import './index.less';

const BianjiGunaliSvg = () => (
  <svg
    id="ic-编辑管理"
    xmlns="http://www.w3.org/2000/svg"
    width="16"
    height="16"
    viewBox="0 0 16 16"
  >
    <path
      id="路径_37918"
      data-name="路径 37918"
      d="M13.892,16H2.111A2.113,2.113,0,0,1,0,13.891V11.75a.7.7,0,0,1,1.406,0v2.141a.7.7,0,0,0,.7.7H13.892a.7.7,0,0,0,.7-.7V2.109a.7.7,0,0,0-.7-.7H2.111a.7.7,0,0,0-.7.7V4.25A.7.7,0,1,1,0,4.25V2.109A2.113,2.113,0,0,1,2.111,0H13.892A2.113,2.113,0,0,1,16,2.109V13.891A2.113,2.113,0,0,1,13.892,16Z"
      transform="translate(-0.001)"
      fill="#fff"
    />
    <path
      id="路径_37919"
      data-name="路径 37919"
      d="M.7,262a.7.7,0,0,1,0-1.406l8.108-.052L6.764,258.5a.7.7,0,0,1,.994-.994l3.231,3.231a.7.7,0,0,1-.492,1.2L.708,262a.006.006,0,0,0,0,0Z"
      transform="translate(0 -253.28)"
      fill="#fff"
    />
    <path
      id="路径_37920"
      data-name="路径 37920"
      d="M420.5,472.441a.7.7,0,0,1-.5-1.2l3.233-3.234a.7.7,0,1,1,.994.994L421,472.234A.7.7,0,0,1,420.5,472.441Z"
      transform="translate(-413.242 -460.491)"
      fill="#fff"
    />
  </svg>
);
type TreeData = {
  title: string;
  icon: JSX.Element;
  key: string;
  pos: [];
  isLeaf?: boolean;
  children?: TreeData;
}[];

type IProps = {
  value: choeseData;
  categoryType: 0 | 1;
  onChange: (value: any) => void;
  expandedKeys: React.Key[];
  setExpandedKeys: (value: React.Key[]) => void;
  ref: Ref<IModelContent>;
  selectId: any;
  setSelectId: any;
};
export type IModelContent = {
  // getData: () => Promise<ImodelDetail['ModelQueryConfig']>;
  // getOldDetail: () => ImodelDetail['ModelQueryConfig'] | undefined;
  // getManyData: IModelRef['getManyData'];
};
const { DirectoryTree } = Tree;

// 定义自己的图标
const BianjiGuanliIcon = (props: any) => (
  <Icon component={BianjiGunaliSvg} {...props} />
);
const ModalContent = (props: IProps, ref: Ref<IModelContent>) => {
  const { value, expandedKeys, setExpandedKeys, categoryType, selectId, setSelectId } = props;
  //   数据
  const [treeData, setTreeData] = useState([]);
  const [selected, setSelected] = useState(value);
  const [selectTreeKey, setSelectTreeKey] = useState(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [pageIndex, setPageIndex] = useState<number>(1);
  const [total, setTotal] = useState<number>(0);
  const [type, setType] = useState('tree');
  const [searchWord, setSearchWord] = useState('tree');
  const [listData, setListData] = useState<any[]>([]);
  const DocConfigRef: any = useRef();
  const [selectedKeys, setSelectedKeys] = useState()

  // 联合完成展开树(受控)
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);

  const { runAsync, loading } = useRequest(getCategoryTree, {
    manual: true,
  });
  // 递归添加子节点
  const addChildNode: (
    selectKey: any,
    treeData: any[],
    children: any[],
  ) => any = (selectKey: any, treeData: any[], children: any[]) => {
    return treeData.map((node) => {
      if (node.key === selectKey) {
        return {
          ...node,
          children,
        };
      }
      if (node.children) {
        return {
          ...node,
          children: addChildNode(selectKey, node.children, children),
        };
      }
      return node;
    });
  };

  // 首次获取树形数据
  useEffect(() => {
    let resTreeData: any = [];
    const params = {
      categoryType: categoryType === 1 ? 1 : 0,
      parentId: categoryType == 1 ? '0000-0000-0001' : '0000-0000-0000',
    };
    categoryType == 1
      ? resTreeData.push({
        title: getMessage('ClassPicker.news'), // 新闻
        icon: (
          <InbizIcon
            type="icon-xinwen"
            style={{ color: 'var(--inbiz-color-primary)' }}
          />
        ),
        key: params.parentId,
        pos: [params.parentId],
        children: [],
      })
      : resTreeData.push({
        title: getMessage('ClassPicker.picture'), // 图片
        icon: (
          <InbizIcon
            type="icon-tupian"
            style={{ color: 'var(--inbiz-color-primary)' }}
          />
        ),
        key: params.parentId,
        pos: [params.parentId],
        children: [],
      });
    // setTreeData(resTreeData)
    runAsync(params).then((data: any) => {
      // resTreeData[0].children=[]
      data.forEach((item: any) => {
        resTreeData[0].children.push({
          title: item.Title,
          icon:
            categoryType == 1 ? (
              <InbizIcon
                type="icon-xinwen"
                style={{ color: 'var(--inbiz-color-primary)' }}
              />
            ) : (
              <InbizIcon
                type="icon-tupian"
                style={{ color: 'var(--inbiz-color-primary)' }}
              />
            ),
          key: item.Key,
          pos: [item.Key],
        });
      });
      setTreeData(resTreeData);
      setExpandedKeys([params.parentId]);
    });
  }, []);

  // 首次进入设置选中值
  useEffect(() => {
    setSelectedKeys(value && value?.map((item: any) => { return item.id }));
    setExpandedKeys([]); // 展开所有父级使用props.value.pos
  }, [props.value]);

  // 设置展开方法
  const onExpand = (expandedKeysValue: React.Key[]) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  // ref：配合完成相关功能
  useImperativeHandle(
    ref,
    () => ({
      getData: async () => {
        setAutoExpandParent(true); // 解决模态框关闭的时候的弹动效果。
        return selected;
      },
      //   getOldDetail: () => modelDetail && modelDetail!.ModelQueryConfig,
      //   getManyData: () => {
      //     return modelRef.current?.getManyData()!
      //   },
    }),
    [selected],
  );

  // 树选中相关的逻辑
  const onCheck = (checkedKeys: any, e: any) => {
    let selectGroup: any[] = []
    e.checkedNodes.map((item: any) => {
      selectGroup.push({
        id: item.key,
        title: item.title,
        pos: item.pos
      })
    })
    setSelected(selectGroup)
    // setSelected({
    //   ...selected,
    //   id: selectedKeysValue[0] as any,
    //   title: info.node.title,
    //   pos: info.selectedNodes[0].pos,
    // });
    setSelectId(e.checkedNodes)
    setSelectedKeys(checkedKeys);
  };

  // 运用递归查找pos（所有父级id）
  const selectPos: (treeData: TreeData, key: string) => React.Key[] = (
    treeData,
    key,
  ) => {
    let resPos = [];
    for (let index = 0; index < treeData.length; index++) {
      if (treeData[index].key == key) {
        resPos = treeData[index].pos;
        return resPos;
      }
      if (treeData[index].children) {
        resPos = selectPos(treeData[index].children, key);
        if (resPos && resPos?.length > 0) {
          return resPos;
        }
      }
    }
  };

  // 加载数据
  const onLoadData = async ({ key, children }: any) => {
    const params = { categoryType: categoryType, parentId: key };
    // 孩子存在的时候直接返回
    if (children) {
      return;
    }
    await runAsync(params).then((data: any) => {
      const childrenData = [];
      data.forEach((item) => {
        let pos = [...selectPos(treeData, key)];
        pos.push(item.Key);
        childrenData.push({
          title: item.Title,
          icon:
            categoryType == 1 ? (
              <InbizIcon
                type="icon-xinwen"
                style={{ color: 'var(--inbiz-color-primary)' }}
              />
            ) : (
              <InbizIcon
                type="icon-tupian"
                style={{ color: 'var(--inbiz-color-primary)' }}
              />
            ),
          key: item.Key,
          pos: pos,
        });
      });
      // // 自动展开多层是需要的逻辑，暂时关闭
      // console.log(childrenData, '插入的孩子节点！')
      // setTimeout(() => {
      //     setExpandedKeys(arr => {
      //         return [...arr]
      //     })
      // }, 0)
      return setTreeData((origin) => addChildNode(key, origin, childrenData));
    });
  };

  // 修改类型（树、表格）
  const typeChage = useCallback((res) => {
    setType(res);
  }, []);

  // 搜索框搜索返回的结果
  const resultChange = useCallback((res) => {
    let newData = res.CmsCategoryList.length
      ? res.CmsCategoryList.map(
        (item: { Key: string; Title: string }, index: number) => {
          return {
            id: item.Key,
            key: item.Key,
            // namePath: item.relativePath.replaceAll('\\', '/'),
            // path: item.path.replaceAll('\\', '/'),
            type: categoryType === 1 ? 1 : 0,
            title: item.Title,
            pos: [item.Key],
          };
        },
      )
      : [];
    setListData((listData) => {
      return [...newData];
    });
    setTotal(res.Total);
  }, []);

  const selectValueFn = (value: choeseData) => {
    setSelected(value);
  };

  return (
    <div>
      <div className="serch">
        <DocSearch
          ref={DocConfigRef}
          {...props}
          resultChange={resultChange}
          typeChage={typeChage}
          pageSize={pageSize}
          topFolderId={selectTreeKey}
          searchChange={(res) => {
            setSearchWord(res);
          }}
        />
        <div className="serchButton">
          <Button
            icon={
              <BianjiGuanliIcon style={{ fontSize: 14 }} />
              // <InbizIcon type="icon-ic-bianjiguanli" style={{ fontSize: 16,color: 'var(--inbiz-color-primary)' }} />
            }
            type="primary"
            className="serchClickText"
            onClick={() =>
              window.open(
                `/inbiz/admin#/content-manage/cms/${categoryType == 1 ? 'newsManage' : 'imageManage'
                }`,
              )
            }
          >
            <span>
              <TextWidget>ClassPicker.configManage</TextWidget>
            </span>
            {/* 配置管理 */}
          </Button>
        </div>
      </div>

      {
        <div className="tree">
          {type == 'tree' ? (
            treeData?.length > 0 && (
              <DirectoryTree
                treeData={treeData}
                loadData={onLoadData}
                height={396}
                showIcon
                blockNode
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                onExpand={onExpand}
                checkedKeys={selectedKeys}
                checkStrictly={true}
                multiple={true}
                checkable={true}
                onCheck={onCheck}
              />
            )
          ) : (
            <DocList
              searchWord={searchWord}
              listData={listData}
              selectValueFn={selectValueFn}
              total={total}
              changeData={(size, pageIndex) => {
                setPageSize(size);
                setPageIndex(pageIndex);
                DocConfigRef?.current?.search(size, pageIndex);
              }}
            />
          )}
        </div>
      }
    </div>
  );
};

export default forwardRef(ModalContent);
